package com.gxa.hualianeshop.base.filter;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author bill
 * @date 2023/8/1 10:19
 */
@Slf4j
//@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    /**
     * 过滤器的过滤执行方法
     * @param exchange spring封装的请求和响应交换对象
     * @param chain 过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //利用交换机对象从前端的请求头中获取token
        String token = exchange.getRequest().getHeaders().getFirst("token");

        // 判断token是否存在
        if (StringUtils.isEmpty(token)) {
            log.info("token不能为空值");

            //利用交换机对象获取response对象
            ServerHttpResponse response = exchange.getResponse();

            // 响应方法,指定响应头为401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 给前端响应json
            //注意,response是spring自己封装的,不能直接调用getWriter, 要使用writeWith方法
            //writeWith 方法的参数是一个Publisher对象
            // 使用alibaba的fastjson快速将数据注入json,并生成字节数组

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code","50002");
            jsonObject.put("msg","缺少token");
            byte[] bytes = jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8);
            // 将字节数组转换为response需要的DataBuffer
            DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(dataBuffer));
        }
        return chain.filter(exchange);
    }
    /**
     * 指定过滤器执行顺序, 越小优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
